package cn.chitanda.weather.data.network

import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

private const val KEY = "fdd88ed3893948f0a64a0b448702e73d"

class NetWorkService {
    private val weatherService = RetrofitCreator.create(WeatherService::class.java)
    private val placeService = RetrofitCreator.create1(PlaceService::class.java)

    suspend fun fetchWeather(location: String) = weatherService.getWeather(location, KEY).await()

    suspend fun searchCity(string: String) = placeService.getCity(string, KEY).await()

    private suspend fun <T> Call<T>.await(): T {
        return suspendCoroutine { continuation ->
            enqueue(object : Callback<T> {
                override fun onFailure(call: Call<T>, t: Throwable) {
                    continuation.resumeWithException(t)
                }

                override fun onResponse(call: Call<T>, response: Response<T>) {
                    val body = response.body()
                    if (body != null) continuation.resume(body)
                    else continuation.resumeWithException(RuntimeException("response body is empty"))
                }

            })
        }
    }

    companion object {
        private var instance: NetWorkService? = null
        fun getInstance() = instance ?: synchronized(this) {
            NetWorkService().also { instance = it }
        }
    }
}